<script setup lang="ts">
import { RouterView, useRoute, useRouter } from 'vue-router'
import { onMounted, computed, ref, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'

interface ChapterConfig {
  id: number
  chapterNumber: number
  chapterTitle: string
  chapterDescription: string
  isActive: boolean
  createdAt: string
  updatedAt: string
}

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 移动端菜单状态
const isMobileMenuOpen = ref(false)
// 章节配置列表
const chapterConfigs = ref<ChapterConfig[]>([])

// 是否显示导航栏（登录和注册页面不显示）
const showNavbar = computed(() => {
  return !['login', 'register'].includes(route.name as string)
})

// 是否显示管理员功能（只有admin角色可见）
const isAdmin = computed(() => {
  return authStore.user?.role === 'admin'
})

// 是否为学生角色
const isStudent = computed(() => {
  return authStore.user?.role === 'student'
})

// 是否显示章节配置功能（admin和teacher角色可见）
const canManageChapters = computed(() => {
  return authStore.user?.role === 'admin' || authStore.user?.role === 'teacher'
})

// 处理登出
const handleLogout = async () => {
  await authStore.logout()
  router.push('/login')
}

// 导航到整合讲义页面
const goToAllLectures = () => {
  router.push('/all-lectures')
}

// 导航到示例代码页面
const goToChapter3Examples = () => {
  router.push('/chapter3-examples')
}

const goToChapter4Examples = () => {
  router.push('/chapter4-examples')
}

const goToExamples = () => {
  router.push('/examples')
}

// 返回首页（学习概览页面）
const goHome = () => {
  router.push('/home')
}

// 导航到思维导图页面
const goToXmind = () => {
  router.push('/xmind')
}

// 导航到前端知识库页面
const goToKnowledgeBase = () => {
  router.push('/knowledge-base')
}

// 导航到管理页面
const goToManagement = () => {
  router.push('/management')
}

// 导航到章节配置页面
const goToChapterConfig = () => {
  router.push('/chapter-config')
}

// 导航到章节要点配置页面
const goToChapterHighlights = () => {
  router.push('/chapter-highlights')
}

// 导航到讲义管理页面
const goToLectureMgr = () => {
  router.push('/lecture-mgr')
}

// 导航到动态章节页面
const goToChapter = (chapterNumber: number) => {
  router.push(`/chapter/${chapterNumber}`)
}

// 加载章节配置列表
const loadChapterConfigs = async () => {
  try {
    const response = await fetch('http://localhost:806/api/chapter-config', {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      // 只显示已启用的章节，并按章节号排序
      if (result.success && Array.isArray(result.data)) {
        const activeConfigs = result.data.filter((config: ChapterConfig) => config.isActive)
        chapterConfigs.value = activeConfigs
          .sort((a: ChapterConfig, b: ChapterConfig) => a.chapterNumber - b.chapterNumber)
      } else {
        chapterConfigs.value = []
      }
    } else {
      chapterConfigs.value = []
    }
  } catch (error) {
    chapterConfigs.value = []
  }
}

// 导航到第1章页面
const goToChapter1 = () => {
  router.push('/chapter1')
}

// 导航到第2章页面
const goToChapter2 = () => {
  router.push('/chapter2')
}

// 切换移动端菜单
const toggleMobileMenu = () => {
  isMobileMenuOpen.value = !isMobileMenuOpen.value
}

// 关闭移动端菜单
const closeMobileMenu = () => {
  isMobileMenuOpen.value = false
}

// 获取按钮样式类（桌面端）
const getButtonClass = (routePath: string) => {
  const isActive = route.path === routePath
  const baseClass = 'px-3 py-1 text-sm rounded transition-colors'

  if (isActive) {
    return `${baseClass} bg-white text-blue-600 shadow-md font-medium`
  } else {
    return `${baseClass} bg-white bg-opacity-20 text-white hover:bg-white hover:text-blue-600`
  }
}

// 获取移动端按钮样式类
const getMobileButtonClass = (routePath: string) => {
  const isActive = route.path === routePath
  const baseClass = 'px-3 py-2 text-sm rounded transition-colors text-center'

  if (isActive) {
    return `${baseClass} bg-white text-blue-600 shadow-md font-medium`
  } else {
    return `${baseClass} bg-white bg-opacity-20 text-white hover:bg-white hover:text-blue-600`
  }
}



// 监听认证状态变化
watch(() => authStore.token, (newToken) => {
  if (newToken) {
    loadChapterConfigs()
  } else {
    chapterConfigs.value = []
  }
})

// 初始化认证状态
onMounted(async () => {
  authStore.restoreAuth()
  
  // 确保认证状态完全恢复后再加载章节配置
  await new Promise(resolve => setTimeout(resolve, 100))
  
  if (authStore.token) {
    await loadChapterConfigs()
  }
})
</script>

<template>
  <div id="app">
    <!-- 导航栏 -->
    <nav v-if="showNavbar && authStore.isAuthenticated" class="fixed top-0 left-0 right-0 z-50 bg-gradient-to-r from-blue-600 via-purple-600 to-blue-700 shadow-lg">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- 桌面端导航 -->
        <div class="hidden lg:flex justify-between h-16">
          <div class="flex items-center space-x-6">
            <button @click="goHome"
              class="text-xl font-semibold text-white hover:text-blue-200 transition-colors cursor-pointer">
              基础篇
            </button>

            <!-- 首页和课程讲义按钮（仅学生可见） -->
            <div v-if="isStudent" class="flex items-center space-x-2">
              <button @click="goHome" :class="getButtonClass('/home')">
                首页
              </button>
            </div>
            <!-- 讲义按钮（仅管理员可见） -->
            <div v-if="isAdmin" class="flex items-center space-x-2">
              <button @click="goToAllLectures" :class="getButtonClass('/all-lectures')">
                讲义
              </button>
            </div>
            
            <!-- 章节按钮（仅学生可见） -->
            <div v-if="isStudent" class="flex items-center space-x-2">
              <!-- 保留原有的静态章节（如果没有对应的动态配置） -->
              <button v-if="!chapterConfigs.some(c => c.chapterNumber === 1)" @click="goToChapter1" :class="getButtonClass('/chapter1')">
                第1章
              </button>
              <button v-if="!chapterConfigs.some(c => c.chapterNumber === 2)" @click="goToChapter2" :class="getButtonClass('/chapter2')">
                第2章
              </button>
              <button v-if="!chapterConfigs.some(c => c.chapterNumber === 3)" @click="goToChapter3Examples" :class="getButtonClass('/chapter3-examples')">
                第3章
              </button>
              <button v-if="!chapterConfigs.some(c => c.chapterNumber === 4)" @click="goToChapter4Examples" :class="getButtonClass('/chapter4-examples')">
                第4章
              </button>
              <button v-if="!chapterConfigs.some(c => c.chapterNumber === 5)" @click="goToExamples" :class="getButtonClass('/examples')">
                第5章
              </button>
              <!-- 动态章节按钮 -->
              <button 
                v-for="config in chapterConfigs" 
                :key="config.id"
                @click="goToChapter(config.chapterNumber)" 
                :class="getButtonClass(`/chapter/${config.chapterNumber}`)"
                :title="config.chapterDescription"
              >
                第{{ config.chapterNumber }}章
              </button>
            </div>
            <!-- 管理功能按钮（仅管理员可见） -->
             <div v-if="isAdmin" class="flex items-center space-x-2">
               <!-- 其他功能按钮 -->
               <button @click="goToXmind" :class="getButtonClass('/xmind')">
                 思维导图
               </button>
               <button @click="goToKnowledgeBase" :class="getButtonClass('/knowledge-base')">
                 前端知识库
               </button>
               <!-- 管理菜单 -->
               <button @click="goToManagement" :class="getButtonClass('/management')">
                 学生进度
               </button>
               <!-- 章节配置菜单（admin和teacher角色可见） -->
               <button v-if="canManageChapters" @click="goToChapterConfig" :class="getButtonClass('/chapter-config')">
                 章节配置
               </button>
               <!-- 章节要点配置菜单（admin和teacher角色可见） -->
               <button v-if="canManageChapters" @click="goToChapterHighlights" :class="getButtonClass('/chapter-highlights')">
                 要点配置
               </button>
               <!-- 讲义管理菜单 -->
               <button @click="goToLectureMgr" :class="getButtonClass('/lecture-mgr')">
                 讲义管理
               </button>
             </div>
          </div>

          <div class="flex items-center space-x-4">
            <span class="text-sm text-white">
              欢迎，{{ authStore.user?.profile?.firstName }} {{ authStore.user?.profile?.lastName }}
              <span class="text-xs text-blue-200">({{ authStore.user?.role }})</span>
            </span>
            <button @click="handleLogout" class="text-sm text-blue-200 hover:text-white transition-colors">
              登出
            </button>
          </div>
        </div>

        <!-- 移动端导航 -->
        <div class="lg:hidden">
          <div class="flex justify-between items-center h-16">
            <!-- Logo -->
            <button @click="goHome" class="text-lg font-semibold text-white hover:text-blue-200 transition-colors">
              基础篇
            </button>

            <!-- 用户信息和汉堡菜单 -->
            <div class="flex items-center space-x-3">
              <span class="text-sm text-white hidden sm:block">
                {{ authStore.user?.profile?.firstName }}
              </span>
              <button @click="toggleMobileMenu"
                class="p-2 rounded-md text-white hover:text-blue-200 hover:bg-white hover:bg-opacity-20 focus:outline-none focus:ring-2 focus:ring-white"
                aria-label="打开菜单">
                <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path v-if="!isMobileMenuOpen" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M4 6h16M4 12h16M4 18h16" />
                  <path v-else stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>

          <!-- 移动端菜单内容 -->
          <div v-if="isMobileMenuOpen" class="border-t border-white border-opacity-30 bg-gradient-to-r from-blue-600 via-purple-600 to-blue-700">
            <div class="px-2 pt-2 pb-3 space-y-1">
              <!-- 首页（仅学生可见） -->
              <div v-if="isStudent" class="mb-4">
                <div class="text-sm font-medium text-blue-200 px-3 py-2">导航</div>
                <div class="grid grid-cols-1 gap-2">
                  <button @click="goHome(); closeMobileMenu()" :class="getMobileButtonClass('/home')">
                    首页
                  </button>
                </div>
              </div>
              <!-- 管理功能（仅管理员可见） -->
               <div v-if="isAdmin" class="mb-4">
                 <div class="text-sm font-medium text-blue-200 px-3 py-2">管理功能</div>
                 <div class="grid grid-cols-2 gap-2">
                   <button @click="goToAllLectures(); closeMobileMenu()" :class="getMobileButtonClass('/all-lectures')">
                     讲义
                   </button>
                   <button @click="() => { router.push('/select'); closeMobileMenu(); }" :class="getMobileButtonClass('/select')">
                     课程练习
                   </button>
                   <button @click="goToXmind(); closeMobileMenu()" :class="getMobileButtonClass('/xmind')">
                     思维导图
                   </button>
                   <button @click="goToKnowledgeBase(); closeMobileMenu()" :class="getMobileButtonClass('/knowledge-base')">
                     前端知识库
                   </button>
                   <button @click="goToManagement(); closeMobileMenu()" :class="getMobileButtonClass('/management')">
                     学生进度
                   </button>
                   <button @click="goToLectureMgr(); closeMobileMenu()" :class="getMobileButtonClass('/lecture-mgr')">
                     讲义管理
                   </button>
                   <!-- 章节配置菜单（admin和teacher角色可见） -->
                   <button v-if="canManageChapters" @click="goToChapterConfig(); closeMobileMenu()" :class="getMobileButtonClass('/chapter-config')">
                     章节配置
                   </button>
                   <!-- 章节要点配置菜单（admin和teacher角色可见） -->
                   <button v-if="canManageChapters" @click="goToChapterHighlights(); closeMobileMenu()" :class="getMobileButtonClass('/chapter-highlights')">
                     要点配置
                   </button>
                 </div>
               </div>

              <!-- 章节内容（仅学生可见） -->
              <div v-if="isStudent" class="mb-4">
                <div class="text-sm font-medium text-blue-200 px-3 py-2">章节内容</div>
                <div class="grid grid-cols-2 gap-2">
                  <!-- 动态章节按钮 -->
                  <button 
                    v-for="config in chapterConfigs" 
                    :key="config.id"
                    @click="goToChapter(config.chapterNumber); closeMobileMenu()" 
                    :class="getMobileButtonClass(`/chapter/${config.chapterNumber}`)"
                    :title="config.chapterDescription"
                  >
                    第{{ config.chapterNumber }}章
                  </button>
                  
                  <!-- 保留原有的静态章节（如果没有对应的动态配置） -->
                  <button v-if="!chapterConfigs.some(c => c.chapterNumber === 1)" @click="goToChapter1(); closeMobileMenu()" :class="getMobileButtonClass('/chapter1')">
                    第1章
                  </button>
                  <button v-if="!chapterConfigs.some(c => c.chapterNumber === 2)" @click="goToChapter2(); closeMobileMenu()" :class="getMobileButtonClass('/chapter2')">
                    第2章
                  </button>
                  <button v-if="!chapterConfigs.some(c => c.chapterNumber === 3)" @click="goToChapter3Examples(); closeMobileMenu()"
                    :class="getMobileButtonClass('/chapter3-examples')">
                    第3章
                  </button>
                  <button v-if="!chapterConfigs.some(c => c.chapterNumber === 4)" @click="goToChapter4Examples(); closeMobileMenu()"
                    :class="getMobileButtonClass('/chapter4-examples')">
                    第4章
                  </button>
                  <button v-if="!chapterConfigs.some(c => c.chapterNumber === 5)" @click="goToExamples(); closeMobileMenu()" :class="getMobileButtonClass('/examples')">
                    第5章
                  </button>
                  

                </div>
              </div>

              <!-- 用户信息和登出 -->
              <div class="border-t border-white border-opacity-30 pt-4">
                <div class="px-3 py-2">
                  <div class="text-sm text-white mb-2">
                    欢迎，{{ authStore.user?.profile?.firstName }} {{ authStore.user?.profile?.lastName }}
                    <span class="text-xs text-blue-200 block">({{ authStore.user?.role }})</span>
                  </div>
                  <button @click="handleLogout(); closeMobileMenu()"
                    class="w-full text-left px-3 py-2 text-sm text-red-300 hover:text-white hover:bg-red-500 hover:bg-opacity-30 rounded transition-colors">
                    登出
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main :class="{ 'pt-0': !showNavbar || !authStore.isAuthenticated, 'pt-16': showNavbar && authStore.isAuthenticated }">
      <RouterView />
    </main>
  </div>
</template>

<style>
#app {
  min-height: 100vh;
  background-color: #f9fafb;
}

main {
  min-height: calc(100vh - 4rem);
}

main.pt-0 {
  min-height: 100vh;
}
</style>
